/**
 * Created by Eoly on 2017/5/2.
 * Call http://palerock.cn
 */

// app按返回键按钮
app.backEvent = function () {
    var model = $('.modal-overlay-visible');

    if (model.length > 0) {
        return;
    }

    var a = $('a.icon-left');
    if (a.length > 0) {
        a.click();
    } else {
        history.back();
    }
    return 'back successfully';
};

// app.isPlusReady = false;
// // 扩展API加载完毕后调用onPlusReady回调函数
// document.addEventListener("plusready", onPlusReady, false);
// // 扩展API加载完毕，现在可以正常调用扩展API
// function onPlusReady() {
//     app.isPlusReady = true;
//     var isPreToExitOne = false;
//     var isPreToExitTwo = false;
//     plus.key.addEventListener('backbutton', function () {
//         if (isPreToExitTwo) {
//             plus.runtime.quit();
//         }
//         if (!isPreToExitOne) {
//             app.backEvent();
//             isPreToExitOne = true;
//             window.setTimeout(function () {
//                 isPreToExitOne = false;
//             }, 500)
//         } else {
//             isPreToExitTwo = true;
//             window.setTimeout(function () {
//                 isPreToExitTwo = false;
//             }, 1500);
//             $.toast('再次按返回键退出', 1500, 'toastToBot');
//         }
//     }, false);
//     plus.geolocation.getCurrentPosition(function (p) {
//         app.addressInfo = p;
//     }, function (e) {
//         console.log("Gelocation Error: code - " + e.code + "; message - " + e.message);
//         switch (e.code) {
//             case e.PERMISSION_DENIED:
//                 $.alert("User denied the request for Geolocation.");
//                 break;
//             case e.POSITION_UNAVAILABLE:
//                 $.alert("Location information is unavailable.");
//                 break;
//             case e.TIMEOUT:
//                 $.alert("The request to get user location timed out.");
//                 break;
//             case e.UNKNOWN_ERROR:
//                 $.alert("An unknown error occurred.");
//                 break;
//         }
//     });
//     setInterval(function () {
//         plus.geolocation.watchPosition(function (p) {
//             app.addressInfo = p;
//         }, function (e) {
//             console.log("Gelocation Error: code - " + e.code + "; message - " + e.message);
//             switch (e.code) {
//                 case e.PERMISSION_DENIED:
//                     $.alert("User denied the request for Geolocation.");
//                     break;
//                 case e.POSITION_UNAVAILABLE:
//                     $.alert("Location information is unavailable.");
//                     break;
//                 case e.TIMEOUT:
//                     $.alert("The request to get user location timed out.");
//                     break;
//                 case e.UNKNOWN_ERROR:
//                     $.alert("An unknown error occurred.");
//                     break;
//             }
//         });
//     }, 10000);
// }

app.filterOptionsAction = function (title, options, locked_index, cb) {

    if (!options.length) {
        return;
    }

    var content = [];

    content.push(
        ' <div class="list-block action-list "><ul>'
    );

    for (var i = 0; i < options.length; i++) {
        if (options[i].value == locked_index) {
            content.push(
                '<li><label class="label-checkbox item-content">\
                     <input type="radio" name="option" value="' + options[i].value + '" checked>\
                     <div class="item-media"><i class="icon icon-form-checkbox"></i></div>\
                      <div class="item-inner">\
                          <div class="item-title">' + options[i].name + '</div>\
                          <div class="item-after">' + (options[i].after ? options[i].after.ele : '') + '</div>\
                       </div>\
                </li></label>'
            );
            continue;
        }
        content.push(
            '<li><label class="label-checkbox item-content">\
                 <input type="radio" name="option" value="' + options[i].value + '">\
                 <div class="item-media"><i class="icon icon-form-checkbox"></i></div>\
                  <div class="item-inner">\
                      <div class="item-title">' + options[i].name + '</div>\
                      <div class="item-after">' + (options[i].after ? options[i].after.ele : '') + '</div>\
                   </div>\
            </label></li>'
        )
    }

    content.push(
        '</ul></div>'
    );

    var htmlText = content.join('');


    var buttons1 = [
        {
            text: title,
            label: true
        },
        {
            text: htmlText,
            label: true
        }
    ];
    var buttons2 = [
        {
            text: '确定',
            bg: 'danger',
            onClick: function (e) {
                var input = $(e).find('input');
                input.each(function () {
                    if ($(this).attr('checked')) {
                        cb.call(window, $(this).val())
                    }
                });
            }
        }
    ];
    var groups = [buttons1, buttons2];
    $.actions(groups);

    // 绑定触发事件
    for (var j = 0; j < options.length; j++) {
        var event = options[j].onclick;
        if (event && event.selector && event.func) {
            $(event.selector).click(event.func);
        }
    }
};

app.getGreatCircleDistance = function (lat1, lng1) {

    if (!app.isPlusReady || !app.addressInfo) {
        return
    }
    var lat2 = app.addressInfo.coords.latitude;
    var lng2 = app.addressInfo.coords.longitude;

    if (lat1 == lat2 && lng1 == lng2) {
        return 1;
    }


    var EARTH_RADIUS = 6378137.0;    //单位M
    var PI = Math.PI;
    var getRad = function (d) {
        return d * PI / 180.0;
    };

    var f = getRad((lat1 + lat2) / 2);
    var g = getRad((lat1 - lat2) / 2);
    var l = getRad((lng1 - lng2) / 2);

    var sg = Math.sin(g);
    var sl = Math.sin(l);
    var sf = Math.sin(f);

    var s, c, w, r, d, h1, h2;
    var a = EARTH_RADIUS;
    var fl = 1 / 298.257;

    sg = sg * sg;
    sl = sl * sl;
    sf = sf * sf;

    s = sg * (1 - sl) + (1 - sf) * sl;
    c = (1 - sg) * (1 - sl) + sf * sl;

    w = Math.atan(Math.sqrt(s / c));
    r = Math.sqrt(s * c) / w;
    d = 2 * w * a;
    h1 = (3 * r - 1) / 2 / c;
    h2 = (3 * r + 1) / 2 / s;


    var distance = d * (1 + fl * (h1 * sf * (1 - sg) - h2 * (1 - sf) * sg));

    return parseInt(distance);
};